﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
using System.Collections;

namespace WaiterService
{
    public class DataTableConverter : JavaScriptConverter
    {
        public override IEnumerable<Type> SupportedTypes
        {
            get { return new Type[] { typeof(DataTable) }; }
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type,
                                           JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            DataTable listType = obj as DataTable;

            if (listType != null)
            {
                // Create the representation.
                Dictionary<string, object> result = new Dictionary<string, object>();
                ArrayList itemsList = new ArrayList();
                foreach (DataRow row in listType.Rows)
                {
                    //Add each entry to the dictionary.
                    Dictionary<string, object> listDict = new Dictionary<string, object>();

                    foreach (DataColumn dc in listType.Columns)
                    {
                        if (dc.DataType == typeof(Byte[]))
                        {
                            if (row[dc] != DBNull.Value)
                                listDict.Add(dc.ColumnName, System.Convert.ToBase64String((Byte[])row[dc]));
                        }
                        else
                            listDict.Add(dc.ColumnName, row[dc]);
                    }
                    itemsList.Add(listDict);
                }
                result["Rows"] = itemsList;


                return result;
            }
            return new Dictionary<string, object>();
        }
    }
}